package com.feinno.urcs.group.service;

import com.feinno.redis.RedisClient;
import com.feinno.urcs.group.api.SmsQuotaService;
import com.feinno.urcs.types.MobileNo;
import com.feinno.util.StringUtils;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceImplementation;

import java.util.Calendar;

/**
 * Created by honghao on 9/24/15.
 */
@ServiceImplementation
public class SmsQuotaServiceImpl implements SmsQuotaService {

	@FieldSetter("${GRPRD}")
	private RedisClient redis;

	private final static String GROUP_SMS_KEY = "GROUP_SMS:";

	@Override
	public void increase(MobileNo mobileNo) {
		redis.incr(getGroupKey(mobileNo));
		long expireAt = getExpireTime();
		redis.expireAt(getGroupKey(mobileNo), expireAt);
	}

	@Override
	public long getSendCount(MobileNo mobileNo) {
		String s = redis.get(getGroupKey(mobileNo));
		if (StringUtils.isNullOrEmpty(s)) {
			return 0;
		}
		return Long.parseLong(s);
	}

	private String getGroupKey(MobileNo mobileNo) {
		return GROUP_SMS_KEY + mobileNo.getMobile();
	}

	public long getExpireTime() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime().getTime() / 1000;
	}
}
